<script setup lang="ts">
import { ref, watch } from 'vue';
import { Modal as AModal, Table, Tag } from 'ant-design-vue';
import type { TableColumnType } from 'ant-design-vue';
import type { ScheduleTaskExecutionRecord } from '@/service/api/schedule-task';
import { fetchScheduleTaskExecutionRecords } from '@/service/api/schedule-task';

interface Props {
  taskId?: string;
  taskName?: string;
}

const props = withDefaults(defineProps<Props>(), {
  taskId: '',
  taskName: ''
});

const visible = defineModel<boolean>('open', {
  default: false
});

const loading = ref(false);
const records = ref<ScheduleTaskExecutionRecord[]>([]);
const expandedRowKeys = ref<string[]>([]);
const isRequesting = ref(false);
const lastRequestedTaskId = ref<string>('');

// 表格列定义
const columns: TableColumnType[] = [
  {
    title: '执行时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: 180
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    width: 180
  },
  {
    title: '执行状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '执行时长',
    dataIndex: 'duration',
    key: 'duration',
    width: 100
  }
];

// 状态配置
const statusConfig = {
  SUCCESS: { color: 'success', text: '成功' },
  FAILED: { color: 'error', text: '失败' },
  RUNNING: { color: 'processing', text: '执行中' }
} as const;

// 获取状态配置
function getStatusConfig(status: string) {
  return statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
}

// 格式化执行时长
function formatDuration(duration: number) {
  if (!duration && duration !== 0) return '-';
  if (duration < 1000) return `${duration}ms`;
  return `${(duration / 1000).toFixed(2)}s`;
}

// 处理展开/收起
function handleExpand(expanded: boolean, record: ScheduleTaskExecutionRecord) {
  expandedRowKeys.value = expanded ? [record.executionId] : [];
}

// 处理关闭
function handleClose() {
  visible.value = false;
  records.value = [];
  expandedRowKeys.value = [];
}

// 处理执行记录数据
function processExecutionRecords(responseData: any) {
  let dataArray = null;

  // 处理直接返回数组的情况
  if (Array.isArray(responseData)) {
    dataArray = responseData;
  }
  // 处理包含data字段的对象格式
  else if (Array.isArray(responseData?.data)) {
    dataArray = responseData.data;
  }
  // 处理标准API响应格式
  else if (responseData?.code === '0000' && Array.isArray(responseData.data)) {
    dataArray = responseData.data;
  }

  if (dataArray && Array.isArray(dataArray)) {
    records.value = dataArray.map((recordData: ScheduleTaskExecutionRecord) => ({
      ...recordData,
      taskName: recordData.taskName || props.taskName || ''
    }));

    // 自动展开第一条记录
    if (records.value.length > 0) {
      expandedRowKeys.value = [records.value[0].executionId];
    }
    return true;
  }
  return false;
}

// 获取执行记录
async function getExecutionRecords() {
  if (!props.taskId || isRequesting.value) {
    return;
  }

  isRequesting.value = true;
  loading.value = true;

  try {
    const response = await fetchScheduleTaskExecutionRecords(props.taskId);
    const responseData = response?.data;

    if (processExecutionRecords(responseData)) {
      // 数据处理成功
    } else {
      records.value = [];
      window.$message?.warning(response?.data?.message || '获取执行记录失败');
    }
  } catch (error: any) {
    console.error('获取执行记录失败:', error);
    window.$message?.error('获取执行记录失败');
    records.value = [];
  } finally {
    loading.value = false;
    isRequesting.value = false;
  }
}

// 监听弹窗显示状态和任务ID变化
watch([() => visible.value, () => props.taskId], ([visi, taskId], [oldVisible, oldTaskId]) => {
  // console.log('Watch triggered:', {
  //   visi,
  //   oldVisible,
  //   taskId,
  //   oldTaskId,
  //   lastRequestedTaskId: lastRequestedTaskId.value
  // });

  if (visi && taskId && ((visi && !oldVisible) || taskId !== oldTaskId)) {
    console.log('Fetching new records');
    lastRequestedTaskId.value = taskId;
    getExecutionRecords();
  }
});
</script>

<template>
  <AModal v-model:open="visible" :title="`${taskName} - 执行记录`" width="1200px" :footer="null" @cancel="handleClose">
    <div class="py-16px">
      <!-- 提示信息 -->
      <Table
        :columns="columns"
        :data-source="records"
        :loading="loading"
        row-key="executionId"
        size="small"
        :pagination="{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total: number) => `共 ${total} 条记录`,
          pageSize: 10,
          defaultPageSize: 10
        }"
        :expanded-row-keys="expandedRowKeys"
        :expand-row-by-click="true"
        @expand="handleExpand"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getStatusConfig(record.status).color">
              {{ getStatusConfig(record.status).text }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'duration'">
            {{ formatDuration(record.duration) }}
          </template>
          <template v-else-if="column.key === 'endTime'">
            {{ record.endTime || '-' }}
          </template>
        </template>

        <template #expandedRowRender="{ record }">
          <div class="border-l-4 border-blue-500 rounded bg-gray-50 p-16px">
            <div class="space-y-16px">
              <!-- 执行日志 -->
              <div v-if="record.logs">
                <div class="mb-6px flex items-center text-gray-700 font-medium">
                  <icon-mdi-file-document class="mr-6px text-blue-500" />
                  执行日志
                </div>
                <div
                  class="max-h-300px overflow-y-auto whitespace-pre-wrap border rounded bg-gray-900 p-12px text-sm text-green-400 font-mono shadow-sm"
                >
                  {{ record.logs }}
                </div>
              </div>

              <!-- 执行结果 -->
              <div v-if="record.result">
                <div class="mb-6px flex items-center text-gray-700 font-medium">
                  <icon-mdi-check-circle class="mr-6px text-green-500" />
                  执行结果
                </div>
                <div class="border rounded bg-white p-12px text-sm text-gray-600 shadow-sm">
                  {{ record.result }}
                </div>
              </div>

              <!-- 错误信息 -->
              <div v-if="record.errorMessage">
                <div class="mb-6px flex items-center text-red-600 font-medium">
                  <icon-mdi-alert-circle class="mr-6px text-red-500" />
                  错误信息
                </div>
                <div class="border border-red-200 rounded bg-red-50 p-12px text-sm text-red-600 shadow-sm">
                  {{ record.errorMessage }}
                </div>
              </div>

              <!-- 无详细信息时的提示 -->
              <div
                v-if="!record.logs && !record.result && !record.errorMessage"
                class="py-24px text-center text-gray-500"
              >
                <icon-mdi-information class="mb-8px text-2xl opacity-50" />
                <div>暂无详细信息</div>
              </div>
            </div>
          </div>
        </template>
      </Table>

      <div v-if="records.length === 0 && !loading" class="py-40px text-center text-gray-500">
        <div class="mb-8px text-lg">暂无执行记录</div>
        <div class="text-sm">该任务还没有执行记录</div>
      </div>
    </div>
  </AModal>
</template>

<style scoped>
:deep(.ant-table-expand-icon-th),
:deep(.ant-table-expand-icon-td) {
  width: 50px;
}

:deep(.ant-table-expanded-row) .ant-table-cell {
  background: #ffffff00 !important;
  padding: 0 !important;
}
</style>
